#!/bin/bash

# dreamy-trac - Automatically install and manage Trac on DreamHost
# Author: Petar Maric <http://www.petarmaric.com>
# Licence: BSD
#
# DON'T CHANGE THIS FILE UNLESS YOU KNOW WHAT YOU'RE DOING!

# Abort on any error
set -e

# Trac version to install
TRAC_VERSION=0.11.1

# Auto-detect Python version
PYTHON_VERSION=`python -c "import sys; print sys.version[:3]"`

# Root directory for all user-specific libraries and programs
PKG_DIR=$HOME/packages

# Root directory for all Trac projects
TRAC_PROJECTS_DIR=$HOME/trac_projects

# Download address for Setup Tools
SETUPTOOLS_URL=http://peak.telecommunity.com/dist/ez_setup.py


echo -n "Are you sure you want to install Trac on this shell account? (y/n) "
read verify
if [ "$verify" == "y" ]; then
    # Create the directories if they don't exist
    [ ! -d ${PKG_DIR} ] && mkdir -p ${PKG_DIR}
    [ ! -d ${TRAC_PROJECTS_DIR} ] && mkdir -p ${TRAC_PROJECTS_DIR}
    
    # Download the required files if they don't exist
    [ ! -f ez_setup.py ] && wget ${SETUPTOOLS_URL}
    
    # Create site-packages directory. Setup Tools script will fail if this
    # directory doesn't exist
    PY_SITE_PACKAGES_DIR=${PKG_DIR}/lib/python${PYTHON_VERSION}/site-packages
    mkdir -p ${PY_SITE_PACKAGES_DIR}
    
    # Install Setup Tools
    python ez_setup.py --prefix=${PKG_DIR}
    
    # Install Trac
    easy_install -eb . --prefix=${PKG_DIR} \
     -f"http://ftp.edgewall.com/pub/trac/Trac-${TRAC_VERSION}.tar.gz" "Trac==${TRAC_VERSION}"
    cd trac
    python setup.py install --prefix=${PKG_DIR}

    # Copy the cgi-bin dir
    mkdir -p ${PKG_DIR}/share/trac
    cp -fr cgi-bin ${PKG_DIR}/share/trac
    
    # Copy the contrib dir
    cp -fr contrib ${PKG_DIR}/share/trac
    
    # Go back to main installation directory
    cd ..
    
    # Install Pygments (used for syntax highlighting)
    easy_install --prefix=${PKG_DIR} Pygments
    
    # Install Account Manager Plugin
    easy_install --prefix=${PKG_DIR} http://trac-hacks.org/svn/accountmanagerplugin/trunk
    
    # Symlink the htdocs dir
    TRAC_EGG_DIR=${PY_SITE_PACKAGES_DIR}/Trac-${TRAC_VERSION}-py${PYTHON_VERSION}.egg/trac
    ln -sf ${TRAC_EGG_DIR}/htdocs/ ${PKG_DIR}/share/trac/htdocs
    
    # Copy templates for post-commit-hook, dispatch.fcgi, .htaccess, ...
    mkdir -p ${PKG_DIR}/share/dreamy-trac
    cp -fr templates ${PKG_DIR}/share/dreamy-trac 
    
    # Copy and setup create_trac_project
    cp -f create_trac_project ${PKG_DIR}/bin/
    perl -pi -e "s|=PYTHON_VERSION_TEMPLATE|=${PYTHON_VERSION}|gi" ${PKG_DIR}/bin/create_trac_project
    perl -pi -e "s|=PKG_DIR_TEMPLATE|=${PKG_DIR}|gi" ${PKG_DIR}/bin/create_trac_project
    perl -pi -e "s|=TRAC_PROJECTS_DIR_TEMPLATE|=${TRAC_PROJECTS_DIR}|gi" ${PKG_DIR}/bin/create_trac_project
    chmod +x ${PKG_DIR}/bin/create_trac_project
    
    
    echo
    echo "You have installed Trac. To create a new trac project run 'create_trac_project.'"
    echo "Thank you for using dreamy-trac :)"
fi

